package Thread;

import java.util.concurrent.PriorityBlockingQueue;

class MyTask1 implements Comparable<MyTask1>{
    public Runnable runnable;
    public long time;

    public MyTask1(Runnable runnable, long time) {
        this.runnable = runnable;
        this.time = time+System.currentTimeMillis();
    }

    @Override
    public int compareTo(MyTask1 o) {
        return (int) (this.time-o.time);
    }
}
class MyTimer1{
    Object object = new Object();
    PriorityBlockingQueue<MyTask1> Queue = new PriorityBlockingQueue<>();
   public void  schedule(Runnable runnable, long time){
       MyTask1 myTask1 = new MyTask1(runnable,time);
       Queue.put(myTask1);
     synchronized (object){
         object.notify();
     }
   }
    public MyTimer1() throws InterruptedException {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    try {

                        synchronized (object){
                            //获取队首元素
                            MyTask1 myTask1 = Queue.take();
                            //获取队首元素当前时间
                            long curTime = myTask1.time;
                            //判断时间是否符合条件
                            if (curTime <= System.currentTimeMillis()){
                                myTask1.runnable.run();
                            }else {
                                //如果不符合条件,为了避免空转,采用wait
                                //先将队首元素添加回去
                                Queue.put(myTask1);
                                object.wait(curTime-System.currentTimeMillis());
                            }

                        }


                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }

                }
            }
        });
        t.start();
    }
}
public class ThreadDemo20 {
    public static void main(String[] args) throws InterruptedException {
        MyTimer1 myTimer1 = new MyTimer1();
       myTimer1.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello1");
            }
        },3000);
        myTimer1.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello2");
            }
        },4000);
        myTimer1.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello3");
            }
        },5000);
        myTimer1.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello4");
            }
        },6000);
        System.out.println();
    }

}
